package com.kerbores.nutz.setup;

import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
import org.nutz.mvc.annotation.At;
import org.nutz.resource.Scans;

import com.kerbores.meeting.domain.Permission;
import com.kerbores.meeting.domain.URLPermission;
import com.kerbores.meeting.domain.Permission.PermissionType;

/**
 * @author Kerbores
 *
 *         Create At 2015年1月9日 下午12:15:51
 */
public class PermissionSetup implements Setup {

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nutz.mvc.Setup#destroy(org.nutz.mvc.NutConfig)
	 */
	@Override
	public void destroy(NutConfig arg0) {
		System.err.println("closing.....");
		try {
			TimeUnit.SECONDS.sleep(10);// 暂时实现一个延迟10秒的关闭功能,这10秒可以用来处理一些业务逻辑
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.err.println("closed!");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nutz.mvc.Setup#init(org.nutz.mvc.NutConfig)
	 */
	@Override
	public void init(NutConfig config) {
		Ioc ioc = config.getIoc();
		Dao dao = ioc.get(Dao.class);// 获取到Dao
		PropertiesProxy initProxy = ioc.get(PropertiesProxy.class, "setup");// 获取到初始化配置

		String modulePackage = initProxy.get("modulePackage", "com.kerbores.module");
		List<Class<?>> classes = Scans.me().scanPackage(modulePackage);// 扫描全部module类
		dao.create(Permission.class, false);
		for (Class<?> clazz : classes) {
			// 获取每个action,按照命名规范插入数据
			String module = null;
			At at = clazz.getAnnotation(At.class);
			if (at != null) {
				module = at.value()[0];
			}
			for (Method method : clazz.getMethods()) {// 遍历方法
				String action = null;
				At actionAt = method.getAnnotation(At.class);
				if (actionAt != null) {
					action = actionAt.value().length >= 1 ? actionAt.value()[0] : method.getName();
					String key = "access:" + (module == null ? action : module + "/" + action);
					// 检查是否存在,不存在则添加
					List<URLPermission> check = dao.query(URLPermission.class, Cnd.where("permissionType", "=", PermissionType.URL).and("key", "=", key));
					if (check == null || check.size() == 0) {
						URLPermission permission = new URLPermission();
						permission.setName("访问权限 " + (module != null ? "module:" + module + "; " : "") + "action:" + action + ";url:"
								+ (module != null ? module + "/" + action : "/" + action));
						permission.setKey(key);
						dao.insert(permission);
					}

				}

			}

		}

	}
}
